import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Search as SearchIcon, Calendar, Eye, PenTool, Filter, X, Tag } from 'lucide-react';
import { useDiaryStore } from '../store/diaryStore';
import { TagBadge } from '../components/TagBadge';
import { format } from 'date-fns';

const moods = [
  { value: '', label: 'All Moods' },
  { value: 'happy', label: '😊 Happy' },
  { value: 'sad', label: '😢 Sad' },
  { value: 'excited', label: '🤩 Excited' },
  { value: 'calm', label: '😌 Calm' },
  { value: 'anxious', label: '😰 Anxious' },
  { value: 'grateful', label: '🙏 Grateful' },
  { value: 'thoughtful', label: '🤔 Thoughtful' },
  { value: 'energetic', label: '⚡ Energetic' },
];

export default function Search() {
  const { 
    entries,
    searchQuery,
    selectedMood,
    selectedTags,
    dateRange,
    setSearchQuery,
    setSelectedMood,
    toggleTag,
    setDateRange,
    getFilteredEntries,
    getPopularTags
  } = useDiaryStore();
  
  const [localSearchQuery, setLocalSearchQuery] = useState(searchQuery);
  const [localSelectedMood, setLocalSelectedMood] = useState(selectedMood);
  const [startDate, setStartDate] = useState(dateRange?.start || '');
  const [endDate, setEndDate] = useState(dateRange?.end || '');
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
  const [searchResults, setSearchResults] = useState(getFilteredEntries());
  const [isSearching, setIsSearching] = useState(false);
  
  const popularTags = getPopularTags(10);
  
  // Update search results when filters change
  useEffect(() => {
    setIsSearching(true);
    const timer = setTimeout(() => {
      setSearchResults(getFilteredEntries());
      setIsSearching(false);
    }, 300);
    
    return () => clearTimeout(timer);
  }, [searchQuery, selectedMood, dateRange, getFilteredEntries]);
  
  const handleSearch = () => {
    setSearchQuery(localSearchQuery);
    setSelectedMood(localSelectedMood);
    
    if (startDate && endDate) {
      setDateRange({ start: startDate, end: endDate });
    } else {
      setDateRange(null);
    }
  };
  
  const clearAllFilters = () => {
    setLocalSearchQuery('');
    setLocalSelectedMood('');
    setStartDate('');
    setEndDate('');
    setSearchQuery('');
    setSelectedMood('');
    useDiaryStore.getState().setSelectedTags([]);
    setDateRange(null);
  };
  
  const formatEntryDate = (dateString: string) => {
    try {
      return format(new Date(dateString), 'MMM dd, yyyy');
    } catch {
      return dateString;
    }
  };
  
  const highlightSearchTerm = (text: string, searchTerm: string) => {
    if (!searchTerm.trim()) return text;
    
    const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
    return text.replace(regex, '<mark class="bg-yellow-200 px-1 rounded">$1</mark>');
  };
  
  const truncateContent = (content: string, maxLength: number = 200) => {
    const textContent = content.replace(/<[^>]*>/g, ''); // Remove HTML tags
    return textContent.length > maxLength 
      ? textContent.substring(0, maxLength) + '...'
      : textContent;
  };
  
  const getMoodEmoji = (mood: string) => {
    const moodData = moods.find(m => m.value === mood);
    return moodData?.label.split(' ')[0] || '📝';
  };
  
  const hasActiveFilters = searchQuery || selectedMood || selectedTags.length > 0 || dateRange;

  return (
    <div className="max-w-6xl mx-auto">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-2xl font-inter font-bold text-forest-green mb-2">
          Search Entries
        </h1>
        <p className="text-warm-gray">
          Find specific entries by content, mood, or date range
        </p>
      </div>
      
      {/* Search Interface */}
      <div className="card mb-8">
        {/* Main Search Bar */}
        <div className="relative mb-6">
          <SearchIcon className="absolute left-4 top-1/2 transform -translate-y-1/2 text-warm-gray w-5 h-5" />
          <input
            type="text"
            placeholder="Search your entries by title or content..."
            value={localSearchQuery}
            onChange={(e) => setLocalSearchQuery(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            className="w-full pl-12 pr-4 py-4 text-lg border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sage focus:border-transparent"
          />
        </div>
        
        {/* Advanced Filters Toggle */}
        <div className="flex items-center justify-between mb-4">
          <button
            onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
            className="flex items-center gap-2 text-sage hover:text-forest-green transition-colors"
          >
            <Filter size={16} />
            {showAdvancedFilters ? 'Hide Advanced Filters' : 'Show Advanced Filters'}
          </button>
          
          {hasActiveFilters && (
            <button
              onClick={clearAllFilters}
              className="flex items-center gap-2 text-warm-gray hover:text-forest-green transition-colors"
            >
              <X size={16} />
              Clear All
            </button>
          )}
        </div>
        
        {/* Advanced Filters */}
        {showAdvancedFilters && (
          <div className="border-t border-gray-200 pt-6 space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {/* Mood Filter */}
              <div>
                <label className="block text-sm font-medium text-warm-gray mb-2">
                  Filter by Mood
                </label>
                <select
                  value={localSelectedMood}
                  onChange={(e) => setLocalSelectedMood(e.target.value)}
                  className="input-field"
                >
                  {moods.map((mood) => (
                    <option key={mood.value} value={mood.value}>
                      {mood.label}
                    </option>
                  ))}
                </select>
              </div>
              
              {/* Date Range */}
              <div>
                <label className="block text-sm font-medium text-warm-gray mb-2">
                  From Date
                </label>
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="input-field"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-warm-gray mb-2">
                  To Date
                </label>
                <input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="input-field"
                />
              </div>
            </div>
            
            {/* Tag Filters */}
            <div>
              <label className="block text-sm font-medium text-warm-gray mb-3">
                <Tag className="inline w-4 h-4 mr-1" />
                Filter by Tags
              </label>
              {selectedTags.length > 0 && (
                <div className="mb-4">
                  <p className="text-xs text-sage mb-2">Selected tags:</p>
                  <div className="flex flex-wrap gap-2">
                    {selectedTags.map((tag) => (
                      <TagBadge
                        key={tag}
                        tag={tag}
                        onRemove={() => toggleTag(tag)}
                        size="sm"
                      />
                    ))}
                  </div>
                </div>
              )}
              {popularTags.length > 0 && (
                <div>
                  <p className="text-xs text-sage mb-2">Available tags:</p>
                  <div className="flex flex-wrap gap-2">
                    {popularTags.map(({ tag, count }) => (
                      <TagBadge
                        key={tag}
                        tag={`${tag} (${count})`}
                        onClick={() => toggleTag(tag)}
                        interactive
                        size="sm"
                      />
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
        
        {/* Search Button */}
        <div className="flex justify-center">
          <button
            onClick={handleSearch}
            className="btn-primary px-8 py-3 text-lg"
            disabled={isSearching}
          >
            {isSearching ? 'Searching...' : 'Search Entries'}
          </button>
        </div>
      </div>
      
      {/* Active Filters Display */}
      {hasActiveFilters && (
        <div className="mb-6">
          <div className="flex flex-wrap gap-2">
            {searchQuery && (
              <span className="inline-flex items-center gap-2 px-3 py-1 bg-sage text-white rounded-full text-sm">
                Search: "{searchQuery}"
                <button
                  onClick={() => {
                    setLocalSearchQuery('');
                    setSearchQuery('');
                  }}
                  className="hover:bg-white hover:bg-opacity-20 rounded-full p-1"
                >
                  <X size={12} />
                </button>
              </span>
            )}
            
            {selectedMood && (
              <span className="inline-flex items-center gap-2 px-3 py-1 bg-forest-green text-white rounded-full text-sm">
                Mood: {moods.find(m => m.value === selectedMood)?.label}
                <button
                  onClick={() => {
                    setLocalSelectedMood('');
                    setSelectedMood('');
                  }}
                  className="hover:bg-white hover:bg-opacity-20 rounded-full p-1"
                >
                  <X size={12} />
                </button>
              </span>
            )}
            
            {selectedTags.length > 0 && selectedTags.map((tag) => (
              <span key={tag} className="inline-flex items-center gap-2 px-3 py-1 bg-forest-green text-white rounded-full text-sm">
                Tag: {tag}
                <button
                  onClick={() => toggleTag(tag)}
                  className="hover:bg-white hover:bg-opacity-20 rounded-full p-1"
                >
                  <X size={12} />
                </button>
              </span>
            ))}
            
            {dateRange && (
              <span className="inline-flex items-center gap-2 px-3 py-1 bg-sage text-white rounded-full text-sm">
                {format(new Date(dateRange.start), 'MMM dd')} - {format(new Date(dateRange.end), 'MMM dd')}
                <button
                  onClick={() => {
                    setStartDate('');
                    setEndDate('');
                    setDateRange(null);
                  }}
                  className="hover:bg-white hover:bg-opacity-20 rounded-full p-1"
                >
                  <X size={12} />
                </button>
              </span>
            )}
          </div>
        </div>
      )}
      
      {/* Search Results */}
      <div>
        {/* Results Header */}
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-lg font-inter font-semibold text-forest-green">
            {isSearching ? 'Searching...' : `${searchResults.length} ${searchResults.length === 1 ? 'result' : 'results'} found`}
          </h2>
          
          {searchResults.length > 0 && (
            <div className="text-sm text-warm-gray">
              Sorted by relevance
            </div>
          )}
        </div>
        
        {/* Results List */}
        {searchResults.length === 0 ? (
          <div className="card text-center py-12">
            {entries.length === 0 ? (
              <>
                <PenTool className="w-16 h-16 text-sage mx-auto mb-4" />
                <h3 className="text-xl font-inter font-semibold text-forest-green mb-2">
                  No entries to search
                </h3>
                <p className="text-warm-gray mb-6">
                  Start writing entries to use the search functionality.
                </p>
                <Link to="/write" className="btn-primary">
                  Write Your First Entry
                </Link>
              </>
            ) : (
              <>
                <SearchIcon className="w-16 h-16 text-sage mx-auto mb-4" />
                <h3 className="text-xl font-inter font-semibold text-forest-green mb-2">
                  No matching entries found
                </h3>
                <p className="text-warm-gray mb-6">
                  Try different search terms or adjust your filters.
                </p>
                <button onClick={clearAllFilters} className="btn-secondary">
                  Clear All Filters
                </button>
              </>
            )}
          </div>
        ) : (
          <div className="space-y-4">
            {searchResults.map((entry) => (
              <div key={entry.id} className="card hover:shadow-md transition-shadow duration-200">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <span className="text-2xl">{getMoodEmoji(entry.mood)}</span>
                      <div>
                        <h3 
                          className="text-lg font-inter font-semibold text-forest-green"
                          dangerouslySetInnerHTML={{
                            __html: highlightSearchTerm(entry.title || 'Untitled Entry', searchQuery)
                          }}
                        />
                        <div className="flex items-center gap-4 text-sm text-sage">
                          <span className="flex items-center gap-1">
                            <Calendar size={14} />
                            {formatEntryDate(entry.date)}
                          </span>
                          {entry.mood && (
                            <span>Mood: {entry.mood}</span>
                          )}
                        </div>
                      </div>
                    </div>
                    
                    <div 
                      className="text-warm-gray mb-3 leading-relaxed"
                      dangerouslySetInnerHTML={{
                        __html: highlightSearchTerm(truncateContent(entry.content), searchQuery)
                      }}
                    />
                    
                    {/* Tags */}
                    {entry.tags && entry.tags.length > 0 && (
                      <div className="mb-4">
                        <div className="flex flex-wrap gap-2">
                          {entry.tags.slice(0, 4).map((tag) => (
                            <TagBadge
                              key={tag}
                              tag={tag}
                              onClick={() => toggleTag(tag)}
                              interactive
                              size="sm"
                            />
                          ))}
                          {entry.tags.length > 4 && (
                            <span className="text-xs text-sage px-2 py-1">
                              +{entry.tags.length - 4} more
                            </span>
                          )}
                        </div>
                      </div>
                    )}
                    
                    <div className="flex items-center gap-3">
                      <Link
                        to={`/entry/${entry.id}`}
                        className="flex items-center gap-2 text-sage hover:text-forest-green transition-colors"
                      >
                        <Eye size={16} />
                        Read Full Entry
                      </Link>
                      
                      <Link
                        to={`/write/${entry.id}`}
                        className="flex items-center gap-2 text-sage hover:text-forest-green transition-colors"
                      >
                        <PenTool size={16} />
                        Edit
                      </Link>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}